package com.wmobile.utils;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.wellsoft.mobileoa.R;
import com.wellsoft.mobileoa.utils.BaseActivity;

public class PopMessageDialog extends Dialog implements Runnable {
	Context baseActivity;
	String title;
	Handler mHandler;
	int dialogResult;
	public static int DialogResultOK = 1;
	public static int DialogResultCANCEL = 0;

	public Thread myThread = null;
	public boolean isRunning = true;

	TextView titleTv;
	Button confirmBtn;
	Button cancelBtn;

	public int getDialogResult() {
		return dialogResult;
	}

	public PopMessageDialog(BaseActivity baseActivity, String title) {
		super(baseActivity, R.style.popDialogTheme);
		this.title = title;
		onCreate();
	}

	public void onCreate() {
		setContentView(R.layout.popconfirmdialog);

		titleTv = (TextView) findViewById(R.id.titletv);
		titleTv.setText(title);

		confirmBtn = (Button) findViewById(R.id.confirmbtn);
		confirmBtn.setOnClickListener(onConfirmListener);

		cancelBtn = (Button) findViewById(R.id.cancelbtn);
		cancelBtn.setVisibility(View.GONE);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			onConfirmListener.onClick(null);
		}

		return super.onKeyDown(keyCode, event);
	}

	View.OnClickListener onConfirmListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			endDialog(DialogResultOK);
		}
	};

	public void endDialog(int result) {
		isRunning = false;
		dismiss();
		dialogResult = result;
		Message m = mHandler.obtainMessage();
		mHandler.sendMessage(m);
	}

	public int showDialog() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message mesg) {
				 throw new RuntimeException();
			}
		};
		myThread = new Thread(this);
		myThread.start();
		super.show();
		try {
			Looper.getMainLooper().loop();
		} catch (Exception e2) {
			e2.printStackTrace();
		}
		return dialogResult;
	}

	@Override
	public void run() {
		int totalTime = 0;
		while (isRunning) {
			try {
				Thread.sleep(100);
				totalTime += 100;
			} catch (InterruptedException e) {
				e.printStackTrace();
				endDialog(DialogResultOK);
				break;
			}
			if (totalTime >= 3000) {
				endDialog(DialogResultOK);
				break;
			}
		}
	}

}
